package com.gucheng.springframework.beans.factory.support;

import com.gucheng.springframework.beans.BeansException;
import com.gucheng.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        //beanDefinition 获取 Class 信息
        Class clazz = beanDefinition.getBeanClass();
        try{
            //判断ctor是否为空，不为空则使用有参构造，否则使用无参构造
            if (null != ctor) {
                //newInstance(args)有参
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }else {
                //无参
                return clazz.getDeclaredConstructor().newInstance();
            }
        }catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e){
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
